package cn.net.xyan.easy.spring.core.config.value;

import cn.net.xyan.easy.spring.core.exception.StatusAndMessageError;
import cn.net.xyan.easy.spring.core.utils.JsonHelper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;

import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by xiashenpin on 16/1/17.
 */
public class JsonConfigValue implements IConfigValue {

    Object rawValue;

    List<Object> enableValues = new LinkedList<>();

    List<Object> disableValues = new LinkedList<>();

    ConfigKey key;

    public JsonConfigValue() {

    }

    private boolean isCollection() {
        Class<?> rawCls = key.getValueType().getRawClass();
        return Collection.class.isAssignableFrom(rawCls);
    }

    @Override
    public void putConfigKey(ConfigKey key) {
        this.key = key;
    }

    @Override
    public void putValue(Object value) {
            if (isCollection()){
                disableValues.clear();
                enableValues.clear();
                enableValues.addAll((Collection<?>) value);
            }else {
                rawValue = value;
            }

    }

    @Override
    public <T> T takeValue(JavaType type) {
        try {
            if (isCollection()) {
                List<Object> result = new LinkedList<>();
                result.addAll(enableValues);
                result.removeAll(disableValues);


                String temp = JsonHelper.objectMapper().writeValueAsString(result);
                return JsonHelper.objectMapper().readValue(temp, type);


            } else if (rawValue != null) {

                return (T)rawValue;

            }
        } catch (IOException e) {
            throw new StatusAndMessageError(-99, e);
        }
        return null;
    }

    @Override
    public void enableValue(Object... values) {
        if (isCollection()) {
            for (Object v:values)
                enableValues.add(v);
        } else {
            throw new StatusAndMessageError(-99, "储存的不是集合类型");
        }
    }

    @Override
    public void disableValue(Object... values) {
        if (isCollection()) {
            for (Object v:values)
                disableValues.add(v);
        } else {
            throw new StatusAndMessageError(-99, "储存的不是集合类型");
        }
    }
}
